<template>
  <transition
    appear
    name="animate__animated animate__bounce"
    enter-active-class="animate__fadeInDown"
    leave-active-class="animate__fadeOutUp"
  >
    <li>
      <label>
        <input type="checkbox" :checked="todo.done" @click="handle(todo.id)" />
        <!-- 如下代码也能实现功能，但不推荐，因为违反原则，修改了props，只是vue没有监视到 -->
        <!-- <input type="checkbox" v-model="todo.done"> -->

        <span v-show="!todo.isEdit">{{ todo.title }}</span>
        <input
          type="text"
          v-show="todo.isEdit"
          :value="todo.title"
          @blur="handleblur(todo, $event)"
          ref="inputTitle"
        />
      </label>
      <button class="btn btn-danger" @click="handledelete(todo.id)">
        删除
      </button>
      <button class="btn btn-edit" @click="handleEdit(todo)">编辑</button>
    </li>
  </transition>
</template>

<script>
import "animate.css";
import pubsub from "pubsub-js";
export default {
  name: "MyItem",
  data() {
    return {};
  },
  methods: {
    //勾选或者取消勾选
    handle(id) {
      //通知app组件将对应的todo的done值取反
      // this.checkTodo(id);
      this.$bus.$emit("checkTodo", id);
    },
    handledelete(id) {
      if (confirm("确定删除这一项吗?")) {
        // this.deleteTodo(id);
        // this.$bus.$emit("deleteTodo", id);
        pubsub.publish("deleteTodo", id);
      }
    },
    handleEdit(todo) {
      if (todo.hasOwnProperty("isEdit")) {
        todo.isEdit = true;
      } else {
        console.log("没有属性");
        this.$set(todo, "isEdit", true);
      }
      // this.$refs.inputTitle.focus();

      //nextTick() 在下一次Dom更新结束后执行其指定的回调
      this.$nextTick(function () {
        this.$refs.inputTitle.focus();
      });
    },
    //失去焦点时才是真正修改todo的内容的时候
    handleblur(todo, e) {
      todo.isEdit = false;
      if (!e.target.value.trim()) return alert("输入不能为空");
      this.$bus.$emit("updateTodo", todo.id, e.target.value);
    },
  },
  props: ["todo"],
};
</script>

<style scoped lang="css">
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
li:hover {
  background-color: #ddd;
}
li:hover button {
  display: block;
}
</style>
